package com.lanou3g.ptp.organize.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanou3g.ptp.entity.Major;
import com.lanou3g.ptp.organize.mapper.MajorMapper;
import com.lanou3g.ptp.organize.service.MajorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class MajorServiceImpl implements MajorService {
    @Autowired
    private MajorMapper majorMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${REDIS_MAJOR_KEY_PREFIX}")
    private String REDIS_MAJOR_KEY_PREFIX;

    @Value("${REDIS_MAJOR_KEY_EXPIRE}")
    private Long REDIS_MAJOR_KEY_EXPIRE;

    @Override
    public void addMajor(Major major) {
        major.setCreateTime(new Date());
        major.setUpdateTime(new Date());
        major.setStatus(0);
        majorMapper.addMajor(major);
    }

    @Override
    public Major findById(Long id) {
        String redisKey = REDIS_MAJOR_KEY_PREFIX + id;
        String sc = redisTemplate.opsForValue().get(redisKey);
        if (sc == null){
            Major major = majorMapper.findById(id);
            String s = JSON.toJSONString(major);
            redisTemplate.opsForValue().set(redisKey,s,REDIS_MAJOR_KEY_EXPIRE, TimeUnit.MINUTES);
            return major;
        }else {
            Major major = JSON.parseObject(sc, Major.class);
            redisTemplate.expire(redisKey,REDIS_MAJOR_KEY_EXPIRE,TimeUnit.MINUTES);
            return major;
        }
    }

    @Override
    public List<Major> findByIds(Long[] ids) {
        List<Major> majors = majorMapper.findByIds(ids);
        return majors;
    }

    @Override
    public Major findByName(String name) {
        Major major = majorMapper.findByName(name);
        return major;
    }

    @Override
    public List<Major> findAll(Integer page,Integer size) {
        Page<Major> pages = PageHelper.startPage(page, size);
        List<Major> majors = majorMapper.findAll();
        return pages;
    }

    @Override
    public void updateById(Long id, Major major) {
        major.setUpdateTime(new Date());
        majorMapper.updateById(id,major);
    }

    @Override
    public void deleteById(Long id) {
        majorMapper.deleteById(id);
    }

    @Override
    public void deleteByIds(Long[] ids) {
        majorMapper.deleteByIds(ids);
    }
}
